package com.wiz.netty.service;

import io.netty.channel.ChannelHandlerContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wiz.data.vo.to.MabDataTO;
import com.wiz.netty.NettyXmlParseFactory;
import com.wiz.netty.message.NettyMessageTO;
import com.wiz.web.manager.ServiceManager;
import com.wiz.web.service.ApiService;
import com.wiz.web.service.AuthorityService;
import com.wiz.web.vo.type.ServiceType;

/**
 * 业务线程总处理
 * @author Hakeny
 */
public class NettyBusinessThread extends NettyThread implements Runnable {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	public NettyBusinessThread(ChannelHandlerContext ctx,NettyMessageTO.MessageContent message,
			ServiceManager serviceManager,NettyXmlParseFactory wizXmlFactory){
		this.ctx = ctx;
		this.message = message;
		this.serviceManager = serviceManager;
		this.wizXmlFactory = wizXmlFactory;
	}

	@Override
	public void run() {
		try {
			//验证密钥
			boolean b = this.checkDynamicMac(message.getMac().toByteArray(), message.getMab().toByteArray(),
					message.getIden().toStringUtf8());
			if(b){
				//根据mti提取封装类
				MabDataTO mabTO = messageDataFactory.getMabDataTO(message.getMab().toByteArray(), message.getMti().toByteArray());
				String dataType = mabTO.getWiz_1_dataType();
				if(dataType.startsWith("f")){
					AuthorityService authorityService = (AuthorityService) serviceManager.getService(ServiceType.AUTHORITY.getId());
					authorityService.handleResquest(message.getIden().toStringUtf8(), mabTO, serviceManager);
				}else if(dataType.startsWith("o")){
					ApiService apiService = (ApiService)serviceManager.getService(ServiceType.API.getId());
					apiService.handleResquest(message.getIden().toStringUtf8(), mabTO, serviceManager);
				}
			}else{
				log.warn("the message that type="+message.getType()+",mab="+message.getMab().toStringUtf8()+
						" from "+message.getIden().toStringUtf8()+" happen mac error");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

}
